import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;


public class Client {
	private Socket socket = null;
	private String seperator = System.getProperty("line.separator");
	private String name;
	public Client(String name){
		this.name = name;
		try {
			socket = new Socket("localhost",9901);
			OutputStream os = socket.getOutputStream();
			startlisten();
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os,"utf-8"));
			writer.write("hello I'm "+name);
			writer.newLine();
			writer.flush();
			//System.out.println("send a msg");
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void startlisten(){
		new Thread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					InputStream is = socket.getInputStream();
					BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));
					String msg = null;
					while((msg = br.readLine()) != null){
						System.out.println(msg);
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return;
				}
				
			}
			
		}).start();
		
		new Thread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(true){
					Scanner sc = new Scanner(System.in).useDelimiter(seperator);
					String msg = sc.next();
					OutputStream os;
					try {
						os = socket.getOutputStream();
						BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,"utf-8"));
						bw.write(name +": "+msg);
						bw.newLine();
						bw.flush();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						return;
					}
					
				}
			}
			
		}).start();
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("input your name:");
		Scanner sc = new Scanner(System.in);
		String name = sc.next();
		new Client(name);
		
	}

}
